<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/blog/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/blog/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="JavaScript," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/images/favicon.ico?v=5.1.2" />






<meta name="description" content="浏览器渲染提高动画的优化不得不提及浏览器是如何渲染一个页面。在从服务器中拿到数据后，浏览器会先做解析三类东西：  解析html,xhtml,svg这三类文档，形成dom树。 解析css，产生css rule tree。 解析js，js会通过api来操作dom tree和css rule tree。  解析完成之后，浏览器引擎会通过dom tree和css rule tree来构建rendering">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="浏览器解析和CSS（GPU）动画优化">
<meta property="og:url" content="https://ipvb.gitee.io/blog/2017/09/16/浏览器解析和CSS（GPU）动画优化/index.html">
<meta property="og:site_name" content="周生东的个人博客">
<meta property="og:description" content="浏览器渲染提高动画的优化不得不提及浏览器是如何渲染一个页面。在从服务器中拿到数据后，浏览器会先做解析三类东西：  解析html,xhtml,svg这三类文档，形成dom树。 解析css，产生css rule tree。 解析js，js会通过api来操作dom tree和css rule tree。  解析完成之后，浏览器引擎会通过dom tree和css rule tree来构建rendering">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://ipvb.gitee.io/blog/2017/09/16/images/t4.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/2017/09/16/images/t3.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/2017/09/16/images/t2.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/2017/09/16/images/t1.png">
<meta property="og:updated_time" content="2022-02-22T05:37:50.083Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="浏览器解析和CSS（GPU）动画优化">
<meta name="twitter:description" content="浏览器渲染提高动画的优化不得不提及浏览器是如何渲染一个页面。在从服务器中拿到数据后，浏览器会先做解析三类东西：  解析html,xhtml,svg这三类文档，形成dom树。 解析css，产生css rule tree。 解析js，js会通过api来操作dom tree和css rule tree。  解析完成之后，浏览器引擎会通过dom tree和css rule tree来构建rendering">
<meta name="twitter:image" content="https://ipvb.gitee.io/blog/2017/09/16/images/t4.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://ipvb.gitee.io/blog/2017/09/16/浏览器解析和CSS（GPU）动画优化/"/>





  <title>浏览器解析和CSS（GPU）动画优化 | 周生东的个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">周生东的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">DailyThoughts & BetterMe</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            站点介绍
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            站内搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://ipvb.gitee.io/blog/blog/2017/09/16/浏览器解析和CSS（GPU）动画优化/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Zhou Sheng Dong">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="周生东的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">浏览器解析和CSS（GPU）动画优化</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-16T20:15:40+08:00">
                2017-09-16
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/blog/2017/09/16/浏览器解析和CSS（GPU）动画优化/" class="leancloud_visitors" data-flag-title="浏览器解析和CSS（GPU）动画优化">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
                 <span>次</span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计</span>
                
                <span title="字数统计">
                  3,545
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长</span>
                
                <span title="阅读时长">
                  13
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="浏览器渲染"><a href="#浏览器渲染" class="headerlink" title="浏览器渲染"></a>浏览器渲染</h2><p>提高动画的优化不得不提及浏览器是如何渲染一个页面。在从服务器中拿到数据后，浏览器会先做解析三类东西：</p>
<ol>
<li>解析html,xhtml,svg这三类文档，形成dom树。</li>
<li>解析css，产生css rule tree。</li>
<li>解析js，js会通过api来操作dom tree和css rule tree。</li>
</ol>
<p>解析完成之后，浏览器引擎会通过dom tree和css rule tree来构建rendering tree：</p>
<ol>
<li>rendering tree和dom tree并不完全相同，例如：<code>&lt;head&gt;&lt;/head&gt;</code>或display:none的东西就不会放在渲染树中。</li>
<li>css rule tree主要是完成匹配，并把css rule附加给rendering tree的每个element。</li>
</ol>
<p>在渲染树构建完成后：</p>
<ol>
<li>浏览器会对这些元素进行定位和布局，这一步也叫做reflow或者layout。<a id="more"></a></li>
<li>浏览器绘制这些元素的样式，颜色，背景，大小及边框等，这一步也叫做repaint。</li>
<li>然后浏览器会将各层的信息发送给GPU，GPU会将各层合成；显示在屏幕上。</li>
</ol>
<h2 id="渲染优化原理"><a href="#渲染优化原理" class="headerlink" title="渲染优化原理"></a>渲染优化原理</h2><p>如上所说，渲染树构建完成后；浏览器要做的步骤：</p>
<p>reflow ——&gt; repaint ——&gt; composite</p>
<ol>
<li><h3 id="reflow和repaint"><a href="#reflow和repaint" class="headerlink" title="reflow和repaint"></a>reflow和repaint</h3><p>reflow和repaint都是耗费浏览器性能的操作，这两者尤以reflow为甚；因为每次reflow，浏览器都要重新计算每个元素的形状和位置。</p>
<p>由于reflow和repaint都是非常消耗性能的，我们的浏览器为此做了一些优化。浏览器会将reflow和repaint的操作积攒一批，然后做一次reflow。但是有些时候，你的代码会强制浏览器做多次reflow。例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">var content = document.getElementById(&apos;content&apos;);</span><br><span class="line"></span><br><span class="line">content.style.width = 700px;</span><br><span class="line"></span><br><span class="line">var contentWidth = content.offsetWidth;</span><br><span class="line"></span><br><span class="line">content.style.backgound = &apos;red&apos;;</span><br></pre></td></tr></table></figure>
<p> 以上第三行代码，需要浏览器reflow后；再获取值，所以会导致浏览器多做一次reflow。</p>
<p>下面是一些针对reflow和repaint的最佳实践：</p>
<ul>
<li><p>不要一条一条地修改dom的样式，尽量使用className一次修改。</p>
</li>
<li><p>将dom离线后修改</p>
<ul>
<li>使用documentFragment对象在内存里操作dom。</li>
<li>先把dom节点display:none;（会触发一次reflow）。然后做大量的修改后，再把它显示出来。</li>
<li>clone一个dom节点在内存里，修改之后；与在线的节点相替换。</li>
</ul>
</li>
<li><p>不要使用table布局，一个小改动会造成整个table的重新布局。</p>
</li>
<li><p>transform和opacity只会引起合成，不会引起布局和重绘。</p>
</li>
</ul>
<p>从上述的最佳实践中你可能发现，动画优化一般都是<strong>尽可能地减少reflow、repaint的发生</strong>。关于哪些属性会引起reflow、repaint及composite，你可以在[这个网站]找到(<a href="https://csstriggers.com/" target="_blank" rel="noopener">https://csstriggers.com/</a>)</p>
</li>
<li><h3 id="composite"><a href="#composite" class="headerlink" title="composite"></a>composite</h3><p>在reflow和repaint之后，浏览器会将多个复合层传入GPU；进行合成工作，那么合成是如何工作的呢？</p>
<p>假设我们的页面中有A和B两个元素，它们有absolute和z-index属性；浏览器会重绘它们，然后将图像发送给GPU；然后GPU将会把多个图像合成展示在屏幕上。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">&lt;style&gt;</span><br><span class="line">#a, #b &#123;</span><br><span class="line">position: absolute;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#a &#123;</span><br><span class="line">left: 30px;</span><br><span class="line">top: 30px;</span><br><span class="line">z-index: 2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#b &#123;</span><br><span class="line">z-index: 1;</span><br><span class="line">&#125;</span><br><span class="line">&lt;/style&gt;</span><br><span class="line">&lt;div id=&quot;#a&quot;&gt;A&lt;/div&gt;</span><br><span class="line">&lt;div id=&quot;#b&quot;&gt;B&lt;/div&gt;</span><br></pre></td></tr></table></figure>
<p><img src="../images/t4.png" alt="blockchain" title="区块链"></p>
<p>在这个例子中，对于动画的每一帧；浏览器会计算元素的几何形状，渲染新状态的图像；并把它们发送给GPU。（你没看错，position也会引起浏览器重排的）尽管浏览器做了优化，在repaint时，只会repaint部分区域；但是我们的动画仍然不够流畅。</p>
<p>因为重排和重绘发生在动画的每一帧，一个有效避免reflow和repaint的方式是我们仅仅画两个图像；一个是a元素，一个是b元素及整个页面；我们将这两张图片发送给GPU，然后动画发生的时候；只做两张图片相对对方的平移。也就是说，仅仅合成缓存的图片将会很快；这也是GPU的优势——它能非常快地以亚像素精度地合成图片，并给动画带来平滑的曲线。</p>
<p>为了仅发生composite，我们做动画的css property必须满足以下三个条件：</p>
<ul>
<li><p>不影响文档流。</p>
</li>
<li><p>不依赖文档流。</p>
</li>
<li><p>不会造成重绘。</p>
</li>
</ul>
<p>满足以上以上条件的css property只有transform和opacity。你可能以为position也满足以上条件，但事实不是这样，举个例子left属性可以使用百分比的值，依赖于它的offset parent。还有em、vh等其他单位也依赖于他们的环境。</p>
<p>我们使用translate来代替left</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">&lt;style&gt;</span><br><span class="line">#a, #b &#123;</span><br><span class="line">position: absolute;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#a &#123;</span><br><span class="line">left: 10px;</span><br><span class="line">top: 10px;</span><br><span class="line">z-index: 2;</span><br><span class="line">animation: move 1s linear;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#b &#123;</span><br><span class="line">left: 50px;</span><br><span class="line">top: 50px;</span><br><span class="line">z-index: 1;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@keyframes move &#123;</span><br><span class="line">from &#123; transform: translateX(0); &#125;</span><br><span class="line">to &#123; transform: translateX(70px); &#125;</span><br><span class="line">&#125;</span><br><span class="line">&lt;/style&gt;</span><br><span class="line">&lt;div id=&quot;#a&quot;&gt;A&lt;/div&gt;</span><br><span class="line">&lt;div id=&quot;#b&quot;&gt;B&lt;/div&gt;</span><br></pre></td></tr></table></figure>
<p>浏览器在动画执行之前就知道动画如何开始和结束，因为浏览器没有看到需要reflow和repaint的操作；浏览器就会画两张图像作为复合层，并将它们传入GPU。</p>
<p>这样做有两个优势：</p>
<ul>
<li><p>动画将会非常流畅</p>
</li>
<li><p>动画不在绑定到CPU，即使js执行大量的工作；动画依然流畅。</p>
</li>
</ul>
<p>看起来性能问题好像已经解决了？在下文你会看到GPU动画的一些问题。</p>
</li>
</ol>
<h2 id="GPU是如何合成图像的"><a href="#GPU是如何合成图像的" class="headerlink" title="GPU是如何合成图像的"></a>GPU是如何合成图像的</h2><p>GPU实际上可以看作一个独立的计算机，它有自己的处理器和存储器及数据处理模型。当浏览器向GPU发送消息的时候，就像向一个外部设备发送消息。</p>
<p>你可以把浏览器向GPU发送数据的过程，与使用ajax向服务器发送消息非常类似。想一下，你用ajax向服务器发送数据，服务器是不会直接接受浏览器的存储的信息的。你需要收集页面上的数据，把它们放进一个载体里面（例如JSON），然后发送数据到远程服务器。</p>
<p>同样的，浏览器向GPU发送数据也需要先创建一个载体；只不过GPU距离CPU很近，不会像远程服务器那样可能几千里那么远。但是对于远程服务器，2秒的延迟是可以接受的；但是对于GPU，几毫秒的延迟都会造成动画的卡顿。</p>
<p>浏览器向GPU发送的数据载体是什么样？这里给出一个简单的制作载体，并把它们发送到GPU的过程。</p>
<ul>
<li>画每个复合层的图像</li>
<li>准备图层的数据</li>
<li>准备动画的着色器（如果需要）</li>
<li>向GPU发送数据</li>
</ul>
<p>所以你可以看到，每次当你添加<strong>transform:translateZ(0)</strong>或<strong>will-change：transform</strong>给一个元素，你都会做同样的工作。重绘是非常消耗性能的，在这里它尤其缓慢。在大多数情况，浏览器不能增量重绘。它不得不重绘先前被复合层覆盖的区域。</p>
<ol>
<li><h3 id="隐式合成"><a href="#隐式合成" class="headerlink" title="隐式合成"></a>隐式合成</h3><p>还记得刚才a元素和b元素动画的例子吗？现在我们将b元素做动画，a元素静止不动。</p>
<p><img src="../images/t3.png" alt="blockchain" title="隐式合成"></p>
<p>和刚才的例子不同，现在b元素将拥有一个独立复合层；然后它们将被GPU合成。但是因为a元素要在b元素的上面（因为a元素的z-index比b元素高），那么浏览器会做什么？浏览器会将a元素也单独做一个复合层！</p>
<p>所以我们现在有三个复合层a元素所在的复合层、b元素所在的复合层、其他内容及背景层。</p>
<p>一个或多个没有自己复合层的元素要出现在有复合层元素的上方，它就会拥有自己的复合层；这种情况被称为隐式合成。</p>
<p>浏览器将a元素提升为一个复合层有很多种原因，下面列举了一些：</p>
<ul>
<li><p>3d或透视变换css属性，例如translate3d,translateZ等等（js一般通过这种方式，使元素获得复合层）</p>
</li>
<li><p><code>&lt;video&gt;&lt;iframe&gt;&lt;canvas&gt;</code><webgl>等元素。</webgl></p>
</li>
<li><p>混合插件（如flash）。</p>
</li>
<li><p>元素自身的 opacity和transform 做 CSS 动画。</p>
</li>
<li><p>拥有css过滤器的元素。</p>
</li>
<li><p>使用will-change属性。</p>
</li>
<li><p>position:fixed。</p>
</li>
<li><p>元素有一个 z-index 较低且包含一个复合层的兄弟元素(换句话说就是该元素在复合层上面渲染)</p>
</li>
</ul>
<p>这看起来css动画的性能瓶颈是在重绘上，但是真实的问题是在内存上：</p>
</li>
<li><h3 id="内存占用"><a href="#内存占用" class="headerlink" title="内存占用"></a>内存占用</h3><p>使用GPU动画需要发送多张渲染层的图像给GPU，GPU也需要缓存它们以便于后续动画的使用。</p>
<p>一个渲染层，需要多少内存占用？为了便于理解，举一个简单的例子；一个宽、高都是300px的纯色图像需要多少内存？</p>
<p>300 300 4 = 360000字节，即360kb。这里乘以4是因为，每个像素需要四个字节计算机内存来描述。</p>
<p>假设我们做一个轮播图组件，轮播图有10张图片；为了实现图片间平滑过渡的交互；为每个图像添加了will-change:transform。这将提升图像为复合层，它将多需要19mb的空间。800 600 4 * 10 = 1920000。</p>
<p>仅仅是一个轮播图组件就需要19m的额外空间！</p>
<p>在chrome的开发者工具中打开setting——》Experiments——》layers可以看到每个层的内存占用。如图所示：</p>
<p><img src="../images/t2.png" alt="blockchain" title="内存占用"></p>
</li>
</ol>
<h2 id="GPU动画的优点和缺点"><a href="#GPU动画的优点和缺点" class="headerlink" title="GPU动画的优点和缺点"></a>GPU动画的优点和缺点</h2><p>现在我们可以总结一下GPU动画的优点和缺点：</p>
<ul>
<li>每秒60帧，动画平滑、流畅。</li>
<li>一个合适的动画工作在一个单独的线程，它不会被大量的js计算阻塞。</li>
<li>3D“变换”是便宜的。</li>
</ul>
<p>缺点：</p>
<ul>
<li>提升一个元素到复合层需要额外的重绘，有时这是慢的。（即我们得到的是一个全层重绘，而不是一个增量）</li>
<li>绘图层必须传输到GPU。取决于层的数量和传输可能会非常缓慢。这可能让一个元素在中低档设备上闪烁。</li>
<li>每个复合层都需要消耗额外的内存，过多的内存可能导致浏览器的崩溃。</li>
<li>如果你不考虑隐式合成，而使用重绘；会导致额外的内存占用，并且浏览器崩溃的概率是非常高的。</li>
<li>我们会有视觉假象，例如在Safari中的文本渲染，在某些情况下页面内容将消失或变形。</li>
</ul>
<h2 id="优化技巧"><a href="#优化技巧" class="headerlink" title="优化技巧"></a>优化技巧</h2><ol>
<li><h3 id="避免隐式合成"><a href="#避免隐式合成" class="headerlink" title="避免隐式合成"></a>避免隐式合成</h3><ol>
<li>保持动画的对象的z-index尽可能的高。理想的，这些元素应该是body元素的直接子元素。当然，这不是总可能的。所以你可以克隆一个元素，把它放在body元素下仅仅是为了做动画。</li>
<li>将元素上设置will-change CSS属性，元素上有了这个属性，浏览器会提升这个元素成为一个复合层（不是总是）。这样动画就可以平滑的开始和结束。但是不要滥用这个属性，否则会大大增加内存消耗。</li>
</ol>
</li>
<li><h3 id="动画中只使用transform和opacity"><a href="#动画中只使用transform和opacity" class="headerlink" title="动画中只使用transform和opacity"></a>动画中只使用transform和opacity</h3><p>如上所说，transform和opacity保证了元素属性的变化不影响文档流、也不受文档流影响；并且不会造成repaint。<br>有些时候你可能想要改变其他的css属性，作为动画。例如：你可能想使用background属性改变背景：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;div class=&quot;bg-change&quot;&gt;&lt;/div&gt;</span><br><span class="line">.bg-change &#123;</span><br><span class="line">  width: 100px;</span><br><span class="line">  height: 100px;</span><br><span class="line">  background: red;</span><br><span class="line">  transition: opacity 2s;</span><br><span class="line">&#125;</span><br><span class="line">.bg-change:hover &#123;</span><br><span class="line">  background: blue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在这个例子中，在动画的每一步；浏览器都会进行一次重绘。我们可以使用一个复层在这个元素上面，并且仅仅变换opacity属性：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&lt;div class=&quot;bg-change&quot;&gt;&lt;/div&gt;</span><br><span class="line">&lt;style&gt;</span><br><span class="line">.bg-change &#123;</span><br><span class="line">  width: 100px;</span><br><span class="line">  height: 100px;</span><br><span class="line">  background: red;</span><br><span class="line">&#125;</span><br><span class="line">.bg-change::before &#123;</span><br><span class="line">  content: &apos;&apos;;</span><br><span class="line">  display: block;</span><br><span class="line">  width: 100%;</span><br><span class="line">  height: 100%;</span><br><span class="line">  background: blue;</span><br><span class="line">  opacity: 0;</span><br><span class="line">  transition: opacity 20s;</span><br><span class="line">&#125;</span><br><span class="line">.bg-change:hover::before &#123;</span><br><span class="line">  opacity: 1;</span><br><span class="line">&#125;</span><br><span class="line">&lt;/style&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><h3 id="减小复合层的尺寸"><a href="#减小复合层的尺寸" class="headerlink" title="减小复合层的尺寸"></a>减小复合层的尺寸</h3><p>看一下两张图片，有什么不同吗？</p>
<p><img src="../images/t1.png" alt="blockchain" title="减少复合层尺寸"></p>
<p>这两张图片视觉上是一样的，但是它们的尺寸一个是39kb；另外一个是400b。不同之处在于，第二个纯色层是通过scale放大10倍做到的。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">&lt;div id=&quot;a&quot;&gt;&lt;/div&gt;</span><br><span class="line">&lt;div id=&quot;b&quot;&gt;&lt;/div&gt;</span><br><span class="line"></span><br><span class="line">&lt;style&gt;</span><br><span class="line">#a, #b &#123;</span><br><span class="line">will-change: transform;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#a &#123;</span><br><span class="line">width: 100px;</span><br><span class="line">height: 100px;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">#b &#123;</span><br><span class="line">width: 10px;</span><br><span class="line">height: 10px;</span><br><span class="line">transform: scale(10);</span><br><span class="line">&#125;</span><br><span class="line">&lt;/style&gt;</span><br></pre></td></tr></table></figure>
<p>对于图片，你要怎么做呢？你可以将图片的尺寸减少5%——10%，然后使用scale将它们放大；用户不会看到什么区别，但是你可以减少大量的存储空间。</p>
</li>
<li><h3 id="用css动画而不是js动画"><a href="#用css动画而不是js动画" class="headerlink" title="用css动画而不是js动画"></a>用css动画而不是js动画</h3><p>css动画有一个重要的特性，它是完全工作在GPU上。因为你声明了一个动画如何开始和如何结束，浏览器会在动画开始前准备好所有需要的指令；并把它们发送给GPU。而如果使用js动画，浏览器必须计算每一帧的状态；为了保证平滑的动画，我们必须在浏览器主线程计算新状态；把它们发送给GPU至少60次每秒。除了计算和发送数据比css动画要慢，主线程的负载也会影响动画； 当主线程的计算任务过多时，会造成动画的延迟、卡顿。</p>
<p>所以尽可能地使用基于css的动画，不仅仅更快；也不会被大量的js计算所阻塞。</p>
</li>
</ol>
<h2 id="优化技巧总结"><a href="#优化技巧总结" class="headerlink" title="优化技巧总结"></a>优化技巧总结</h2><ul>
<li><p>减少浏览器的重排和重绘的发生。</p>
</li>
<li><p>不要使用table布局。</p>
</li>
<li><p>css动画中尽量只使用transform和opacity，这不会发生重排和重绘。</p>
</li>
<li><p>尽可能地只使用css做动画。</p>
</li>
<li><p>避免浏览器的隐式合成。</p>
</li>
<li><p>改变复合层的尺寸。</p>
</li>
</ul>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><p>GPU合成主要参考：</p>
<p><a href="https://www.smashingmagazine" target="_blank" rel="noopener">https://www.smashingmagazine….</a></p>
<p>哪些属性会引起reflow、repaint及composite，你可以在这个网站找到：</p>
<p><a href="https://csstriggers.com" target="_blank" rel="noopener">https://csstriggers.com/</a></p>

      
    </div>
    
    
    

    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------------ Come to an end <i class="fa fa-apple"></i> Thank you for reading ------------</div>
    
</div>
      
    </div>

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/JavaScript/" rel="tag"><i class="fa fa-tag"></i> JavaScript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2017/07/31/理解-ES6-的-async-await/" rel="next" title="理解 ES6 的 async/await">
                <i class="fa fa-chevron-left"></i> 理解 ES6 的 async/await
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2017/12/12/竞品分析：在线K12教育【轻学堂】/" rel="prev" title="竞品分析：在线K12教育【轻学堂】">
                竞品分析：在线K12教育【轻学堂】 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjI5NC84ODU1"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/avatar.gif"
               alt="Zhou Sheng Dong" />
          <p class="site-author-name" itemprop="name">Zhou Sheng Dong</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives/">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories/index.html">
                <span class="site-state-item-count">2</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags/index.html">
                <span class="site-state-item-count">2</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zhoushengdong" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/dante0729" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-send"></i>
                  
                    
                      知乎
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="mailto:www.124780540@qq.com" target="_blank" title="E-Mail">
                  
                    <i class="fa fa-fw fa-envelope"></i>
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="/blog/images/ecode.jpg" target="_blank" title="微信">
                  
                    <i class="fa fa-fw fa-weixin"></i>
                  
                    
                      微信
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="https://music.163.com/#/user/home?id=135364313" title="网易云音乐" target="_blank">网易云音乐</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.ruanyifeng.com/home.html" title="阮一峰" target="_blank">阮一峰</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#浏览器渲染"><span class="nav-number">1.</span> <span class="nav-text">浏览器渲染</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#渲染优化原理"><span class="nav-number">2.</span> <span class="nav-text">渲染优化原理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#reflow和repaint"><span class="nav-number">2.1.</span> <span class="nav-text">reflow和repaint</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#composite"><span class="nav-number">2.2.</span> <span class="nav-text">composite</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#GPU是如何合成图像的"><span class="nav-number">3.</span> <span class="nav-text">GPU是如何合成图像的</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#隐式合成"><span class="nav-number">3.1.</span> <span class="nav-text">隐式合成</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#内存占用"><span class="nav-number">3.2.</span> <span class="nav-text">内存占用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#GPU动画的优点和缺点"><span class="nav-number">4.</span> <span class="nav-text">GPU动画的优点和缺点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#优化技巧"><span class="nav-number">5.</span> <span class="nav-text">优化技巧</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#避免隐式合成"><span class="nav-number">5.1.</span> <span class="nav-text">避免隐式合成</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#动画中只使用transform和opacity"><span class="nav-number">5.2.</span> <span class="nav-text">动画中只使用transform和opacity</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#减小复合层的尺寸"><span class="nav-number">5.3.</span> <span class="nav-text">减小复合层的尺寸</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用css动画而不是js动画"><span class="nav-number">5.4.</span> <span class="nav-text">用css动画而不是js动画</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#优化技巧总结"><span class="nav-number">6.</span> <span class="nav-text">优化技巧总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">7.</span> <span class="nav-text">参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

      <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=64293&auto=1&height=66"></iframe>

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2014 - 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zhou Sheng Dong</span>
</div>

<!--
<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>
-->

<!-- <div class="theme-info">
  <div class="powered-by"></div>
  <i class="fa fa-file-word-o" aria-hidden="true"></i>
  <span class="post-count">博客全站共 20.1k字</span>
</div>
-->
        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"> You are</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      Visitor of this site, welcome~
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"> Page View</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  <!-- 来必力City版安装代码 -->
  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
    <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
  
  <!-- City版安装代码已完成 -->





  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("bVaMPlLlY6iLfKTJxt2dwg2W-gzGzoHsz", "wUyT08JP6LOCTUtp6jMn0oIY");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
